package com.gnetek.netty.thread;

import com.gnetek.netty.client.EchoClient;
import com.gnetek.netty.contact.Contact;
import com.gnetek.netty.contact.SequenceFactory;
import com.gnetek.netty.controller.NettyClientController;
import com.gnetek.netty.interf.NettyController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description 发送心跳数据
 * @Author Darren Huang
 * @Date 2022-11-22 14:40
 */
public class HeartJumpRunner implements Runnable{
    private Logger log = LoggerFactory.getLogger(HeartJumpRunner.class);

    private String beehiveId;
    private Integer sec;
    private NettyController nettyCtrl;

    private static boolean run;

    public static void doStart(String beehiveId, Integer sec, NettyController nettyCtrl){
        run = true;
        new Thread(new HeartJumpRunner(beehiveId, sec, nettyCtrl)).start();
    }
    public static void doStop(){run = false;}

    private HeartJumpRunner(String beehiveId, Integer sec, NettyController nettyCtrl){
        this.beehiveId =beehiveId;
        this.sec =sec;
        this.nettyCtrl = nettyCtrl;
    }

    @Override
    public void run() {
        while (run){
            if(EchoClient.getInstance()==null || !EchoClient.getInstance().isConnent()) {
                run=false;
            }else {
                String seq = String.format( "%08x", SequenceFactory.nextSequence());
                String cmd = String.format(Contact.COMMAND_0001, seq, beehiveId).toUpperCase();
                EchoClient.getInstance().sendHexCmd(cmd);
                nettyCtrl.showMsg(cmd, true);
                log.info("{}发送成功。", cmd);
                try {
                    Thread.sleep(sec * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
